//
//  XWXNetWorkQuery.m
//  YuChangWL
//
//  Created by Mr_hi on 2018/12/19.
//  Copyright © 2018 zwhl. All rights reserved.
//

#import "XWXNetWorkQuery.h"
#import "AFNetworking.h"
#import <AFNetworkActivityIndicatorManager.h>
#import "NSError+XWXError.h"

@interface XWXNetWorkQuery ()

/** 网络请求管理 */
@property (nonatomic, strong) AFHTTPSessionManager *manage;

@end

@implementation XWXNetWorkQuery

static XWXNetWorkQuery *instance;

+(instancetype)sharedManage{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[XWXNetWorkQuery alloc]init];
    });
    return instance;
}

#pragma mark - 常规请求
- (void)AFRequestData:(NSString*)urlString HttpMethod:(NSString*)method HaveToken:(BOOL)token params:(NSMutableDictionary*)parms
     completionHandle:(void(^)(id result))completionBlock errorHandle:(void(^)(NSError* error))errorBlock {
    if (token == YES) {
        parms[@"token"] = [LCUserCenter objectForKey:klogin_cre];
        NSLog(@"token = %@ userId = %@",[LCUserCenter objectForKey:klogin_cre],[LCUserCenter objectForKey:Userid]);
    }
    // 打印请求网址链接
    NSString *urlStr = @"";
    for (NSString * key in parms.allKeys) {
        urlStr = [urlStr stringByAppendingFormat:@"%@=%@&",key,parms[key]];
    }
    urlStr = [NSString stringWithFormat:@"%@&%@",urlString,urlStr];
    NSLog(@"请求地址：%@",urlStr);
    
    NSString *URL = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    if ([method isEqualToString:@"GET"]) {
        [self.manage GET:URL parameters:parms headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            //进度
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            // 成功 回调block，传递得到的参数
            completionBlock([self dicWithData:responseObject]);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            // 失败
            errorBlock([NSError returnErrorWithError:error]);
        }];
    }else if ([method isEqualToString:@"POST"]){
        [self.manage POST:URL parameters:parms headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
            //进度
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            // 成功 回调block，传递得到的参数
            completionBlock([self dicWithData:responseObject]);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            // 失败
            errorBlock([NSError returnErrorWithError:error]);
        }];
    }
}


//－－－POST上传文件
//使用multipart协议 @{@"Content-Type":@"form-data"} 上传文件的方法：
//multipart是HTTP协议为web表单新增的上传文件的协议，数据也是放在请求体中，和普通POST的区别是参数不再是key＝value格式，而是特定的数据格式。
#pragma mark - 仅上传图片方法
-(void)AFPostData:(NSString*)urlString data:(NSMutableArray *)Imagedatas completionHandle:(void (^)(id))completionBlock errorHandle:(void (^)(NSError *error))errorBlock {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = 10;
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
    
    [manager POST:urlString parameters:Imagedatas headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
           // 处理图片
           int i = 0;
           for (UIImage *image in Imagedatas) {
               NSLog(@"image-%d - %@",i,image);
               NSData *data = UIImageJPEGRepresentation(image,.3);
               [formData appendPartWithFileData:data name:[NSString stringWithFormat:@"%d",i] fileName:@"test.jpg" mimeType:@"image/jpg"];
               i++;
           }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        completionBlock([self dicWithData:responseObject]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 失败
        errorBlock([NSError returnErrorWithError:error]);
    }];
}

#pragma mark - 图片上传（带参数）
-(void)AfPostUrl:(NSString *)urlStr params:(NSMutableDictionary *)params HaveToken:(BOOL)token imgsData:(NSMutableDictionary *)ImageData completionHandle:(void(^)(id result))completionBlock errorHandle:(void(^)(NSError* error))errorBlock {
    if (token == YES) {
        params[@"token"] = [LCUserCenter objectForKey:klogin_cre];
    }
    params[@"Fmtoutput"] = @"json";
    
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    manger.requestSerializer = [AFHTTPRequestSerializer serializer];
    manger.requestSerializer.timeoutInterval = 10;
    manger.responseSerializer = [AFHTTPResponseSerializer serializer];
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
    [manger POST:urlStr parameters:params headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (NSString *keyName in ImageData) {
            if ([ImageData[keyName] isKindOfClass:[UIImage class]]) {
                UIImage *image = ImageData[keyName];
                NSData *data = UIImageJPEGRepresentation(image,.3);
                // 需要上传的数据添加到formData中(name必为键值)
                [formData appendPartWithFileData:data name:keyName fileName:@"test.jpg" mimeType:@"image/jpg"];
            } else {
                // 处理图片
                [ImageData[keyName] enumerateObjectsUsingBlock:^(UIImage *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    UIImage *image = obj;
                    NSData *data = UIImageJPEGRepresentation(image,.3);
                    [formData appendPartWithFileData:data name:[NSString stringWithFormat:@"%@%ld",keyName,idx] fileName:@"test.jpg" mimeType:@"image/jpg"];
                }];
            }
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        completionBlock([self dicWithData:responseObject]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 失败
        errorBlock([NSError returnErrorWithError:error]);
    }];
}

#pragma mark - data转换为字典
-(NSDictionary *)dicWithData:(NSData *)data
{
    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSData *postdata = [string dataUsingEncoding:NSUTF8StringEncoding];
    return [NSJSONSerialization JSONObjectWithData:postdata options:NSJSONReadingMutableLeaves error:nil];
}

#pragma mark - 网络请求管理器
- (AFHTTPSessionManager *)manage
{
    if (!_manage) {
        _manage = [AFHTTPSessionManager manager];
        // 请求数据慢的时候，我们手机的左上角会出现菊花的效果
        [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
        /** 参数编码的序列化器 */
        _manage.requestSerializer = [AFHTTPRequestSerializer serializer];
        _manage.requestSerializer.timeoutInterval  = 10;
        /** 返回内容编码的序列化器 */
        _manage.responseSerializer = [AFHTTPResponseSerializer serializer];
        _manage.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/plain", @"text/javascript", @"text/xml", @"image/*", nil];
        
    }return _manage;
}



@end


